package com.bigdata.security.shiro.matcher;/**
 * Created by Administrator on 2019/7/18 0018.
 */

import com.bigdata.common.constant.Constants;
import com.bigdata.common.constant.ShiroConstants;
import com.bigdata.model.User;
import com.bigdata.utils.shiro.ShiroUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.codec.CodecSupport;

import static org.apache.shiro.web.filter.mgt.DefaultFilter.user;

/**
 * @author Administrator
 * @description
 * @date 2019/7/18 0018
 **/
public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher {
    private EhCacheManager cacheManager;
    private int maxRetryCount = 5;

    public EhCacheManager getCacheManager() {
        return cacheManager;
    }

    public void setCacheManager(EhCacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }

    /**
     * @param token, info
     * @return boolean
     * @Author lly
     * @Date 2019/7/18 0018
     * @Description 用户输入错误密码5次 限制等待5分钟
     */
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        Cache<Object, Object> cache = cacheManager.getCache(ShiroConstants.LOGINRECORDCACHE);
        //使用本地缓存判断用户登录限制次数
        if (token instanceof UsernamePasswordToken) {
            UsernamePasswordToken utk = (UsernamePasswordToken) token;
            String salt = "";
            String pwd = "";
            if (info instanceof SaltedAuthenticationInfo) {
                SaltedAuthenticationInfo saltinfo = (SaltedAuthenticationInfo) info;
                salt = CodecSupport.toString(saltinfo.getCredentialsSalt().getBytes(), "UTF-8");
                pwd = (String) saltinfo.getCredentials();
            }
            String password = new String(utk.getPassword());
            String mm = ShiroUtils.sha256(password, salt);
            if (!(pwd.equals(mm))) {
                return false;
            }
        }
        return true;
    }
}
